import { defineStore } from "pinia";
import { getUserInfo } from "../api/user";
import { getStoreMainInfo } from "../api/store";

import { clearStorage, fixed, setStorage, getStorage } from "../utils/common";

export default defineStore("main", {
  state: () => {
    return {
      isLogin: true,
      location: {
        longitude: "104.065833",
        latitude: "30.657834",
        address: "天府广场",
      },
      companyInfo: {},
      sceneCode: "",
      isLoginModal: false,
      userInfo: {
        nickName: "",
        userHeadUrl: "",
        authStatus: "",
        accountAmount: 0,
        merchantRevenue: 0,
        piccPoints: 0,
        mobile: "",
        invitation: "",
        merchantEntryStatus: "",
        isWxLogin: "",
        unReadNoticeCount: 0,
        isClerk: 0,
        userId: "",
        isRecommend: "",
        vip: "0",
        provinceName: "",
        cityName: "",
        countyName: "",
        address: "",
        userName: "",
        userMobile: "",
      },
      projectList: [],
      storeInfo: {
        isRecommend: "",
        accountAmount: 0,
        doorPhotoUrl: "",
        invitation: "",
        merchantRevenue: 0,
        monthMerchantRevenue: 0,
        storeName: "",
        todayMerchantRevenue: 0,
        vip: 0,
        storeRate: 0,
        endMarketRate: 0,
        startMarketRate: 0,
        status: "",
        saleNum: 0,
        clerkRate: "",
        discountAmountRate: 0,
        merType: "0",
        businessType: "",
      },
      oilUrl: "",
      shopForm: {
        storeId: "",
        allPrice: 0,
        allDiscountPrice: 0,
        shopList: [],
        shopNum: 0,
      },
      homeScrollList: [],
      lifeScrollList: <any>[],
      dictTypes: {} as Record<string, any>,
    };
  },
  actions: {
    setLocation(data: {
      longitude: number | string;
      latitude: number | string;
      address?: string;
    }) {
      this.location.longitude = data.longitude;
      this.location.latitude = data.latitude;
      this.location.address = data.address;
    },

    async setUserInfo() {
      const { data } = await getUserInfo();
 
      this.userInfo = {
        ...data,
        totalAmount: (
          Number(data.amount || 0) +
          Number(data.chargingAmount || 0) +
          Number(data.merchantAmount || 0) +
          Number(data.channelAmount || 0)
        ).toFixed(2),
      };
      const userList = getStorage("userList");
      const token = getStorage("token");
      this.setIsLoginModal(false);

      if (!userList?.length) {
        setStorage("userList", [
          { userId: data.userId, token: token, nickName: data.nickName, mobile: data.mobile },
        ]);
        return;
      }
      if (!userList.some((item: any) => item.userId === data.userId)) {
        setStorage("userList", [
          ...(userList || []),
          { userId: data.userId, token: token, nickName: data.nickName, mobile: data.mobile },
        ]);
      }
    },
    async setStoreInfo() {
      const { data } = await getStoreMainInfo();
      this.storeInfo = data;
    },

    setGoodOrder(data: any) {
      this.goodsOrder = data;
    },
    setCompanyInfo(data: any) {
      this.companyInfo = data;
    },
    setSceneCode(data: string) {
      this.sceneCode = data;
    },
    setIsLogin(data: boolean) {
      this.isLogin = data;
    },
    setIsLoginModal(data: boolean) {
      this.isLoginModal = data;

    },
    loginOut() {
      clearStorage("token");
      clearStorage("userId");
      clearStorage("check_user");
      clearStorage("openId");
      clearStorage("userHeadUrl");
      clearStorage("doorPhotoUrl");
      clearStorage("appShow");
      clearStorage("historyUser");
      setStorage("checkTab", 0);
  
      this.userInfo = {
        nickName: "",
        userHeadUrl: "",
        authStatus: "",
      };

    },
    setOilUrl(url: string) {
      this.oilUrl = url;
    },
    addShopForm(data: any) {
      const index = this.shopForm.shopList.findIndex(
        (item: { serviceId: string }) => item.serviceId === data.serviceId
      );
      if (index !== -1) {
        this.shopForm.shopList[index].dataNum++;
        this.shopForm.shopList[index].dataPrice = fixed(
          this.shopForm.shopList[index].dataPrice + data.price,
          2
        );
        this.shopForm.shopList[index].dataDiscountPrice = fixed(
          this.shopForm.shopList[index].dataDiscountPrice + data.discountPrice,
          2
        );
      } else {
        this.shopForm.shopList.push({
          ...data,
          dataNum: 1,
          dataPrice: data.price,
          dataDiscountPrice: data.discountPrice,
        });
      }
      this.shopForm.allPrice = fixed(this.shopForm.allPrice + data.price, 2);
      this.shopForm.allDiscountPrice = fixed(
        this.shopForm.allDiscountPrice + data.discountPrice,
        2
      );
      this.shopForm.shopNum++;
    },
    removeShopForm(data: any) {
      const index = this.shopForm.shopList.findIndex(
        (item: { serviceId: string }) => item.serviceId === data.serviceId
      );
      this.shopForm.shopList[index].dataNum--;
      this.shopForm.shopList[index].dataPrice = fixed(
        this.shopForm.shopList[index].dataPrice - data.price,
        2
      );
      this.shopForm.shopList[index].dataDiscountPrice = fixed(
        this.shopForm.shopList[index].dataDiscountPrice - data.discountPrice,
        2
      );
      if (this.shopForm.shopList[index].dataNum <= 0) {
        this.shopForm.shopList.splice(index, 1);
      }
      this.shopForm.allPrice = fixed(this.shopForm.allPrice - data.price, 2);
      this.shopForm.allDiscountPrice = fixed(
        this.shopForm.allDiscountPrice - data.discountPrice,
        2
      );
      this.shopForm.shopNum--;
    },
    clearShopForm() {
      this.shopForm.allPrice = 0;
      this.shopForm.allDiscountPrice = 0;
      this.shopForm.shopList = [];
      this.shopForm.shopNum = 0;
    },
    addProjectList(data: { id: string }) {
      if (!this.projectList.length) {
        this.projectList.push({ ...data, num: 1 });
        return;
      }
      const index = this.projectList.findIndex((i) => i.id === data.id);
      if (index === -1) {
        this.projectList.push({ ...data, num: 1 });
      } else {
        this.projectList.splice(index, 1);
      }
      console.log(this.projectList, "datata");
    },
    changeProjectList(id: string, step: string) {
      const index = this.projectList.findIndex(
        (i: { id: string }) => i.id === id
      );
      if (step === "add") {
        this.projectList[index].num++;
      } else if (step === "delete") {
        this.projectList.splice(index, 1);
      } else {
        this.projectList[index].num--;
        this.projectList[index].num <= 0 && this.projectList.splice(index, 1);
      }
    },
  },
});
